// 任务控制器
import taskService from '../services/taskService.ts';
import { successResponse, errorResponse } from '../utils/response.ts';
import type { FastifyRequest, FastifyReply } from 'fastify';

// 定义创建任务请求体类型
interface CreateTaskBody {
  group_id: number;
  title: string;
  description?: string;
  is_important?: boolean;
  is_my_day?: boolean;
  due_date?: string;
}

// 定义更新任务请求体类型
interface UpdateTaskBody {
  group_id?: number;
  title?: string;
  description?: string;
  is_important?: boolean;
  is_my_day?: boolean;
  status?: string;
  due_date?: string;
}

// 定义更新任务分组请求体类型
interface UpdateTaskGroupBody {
  group_id: number;
}

// 定义任务查询参数类型
interface TaskQueryParams {
  group_id?: string;
  status?: string;
}

// 定义路由参数类型
interface TaskParams {
  taskId: string;
}

/**
 * 创建任务控制器
 * 处理创建新任务的请求
 * @param {FastifyRequest} request - Fastify请求对象，包含任务信息
 * @param {FastifyReply} reply - Fastify响应对象
 * @returns {Promise<FastifyReply>} 创建结果响应
 */
async function createTask(request: FastifyRequest<{ Body: CreateTaskBody }>, reply: FastifyReply): Promise<FastifyReply> {
  try {
    const { group_id, title, description, is_important, is_my_day, due_date } = request.body;
    const userId = request.user?.userId; // 从认证中间件获取用户ID
    if (!userId) {
      return reply.code(401).send(errorResponse('用户未登录', 401));
    }
    const result = await taskService.createTask(
      userId, 
      group_id, 
      title, 
      description, 
      is_important, 
      is_my_day, 
      due_date
    );
    return reply.send(successResponse(result, '创建成功'));
  } catch (err) {
    return reply.code(400).send(errorResponse((err as Error).message, 10001));
  }
}

/**
 * 获取任务列表控制器
 * 处理获取用户任务列表的请求
 * @param {FastifyRequest} request - Fastify请求对象，包含查询参数
 * @param {FastifyReply} reply - Fastify响应对象
 * @returns {Promise<FastifyReply>} 任务列表响应
 */
async function getTasks(request: FastifyRequest<{ Querystring: TaskQueryParams }>, reply: FastifyReply): Promise<FastifyReply> {
  try {
    const userId = request.user?.userId; // 从认证中间件获取用户ID
    if (!userId) {
      return reply.code(401).send(errorResponse('用户未登录', 401));
    }
    const { group_id, status } = request.query;
    const result = await taskService.getTasks(userId, group_id ? parseInt(group_id) : undefined, status);
    return reply.send(successResponse(result, '获取成功'));
  } catch (err) {
    return reply.code(500).send(errorResponse((err as Error).message, 10006));
  }
}

/**
 * 获取"我的一天"任务控制器
 * 处理获取用户标记为"我的一天"的任务列表的请求
 * @param {FastifyRequest} request - Fastify请求对象
 * @param {FastifyReply} reply - Fastify响应对象
 * @returns {Promise<FastifyReply>} "我的一天"任务列表响应
 */
async function getMyDayTasks(request: FastifyRequest, reply: FastifyReply): Promise<FastifyReply> {
  try {
    const userId = request.user?.userId; // 从认证中间件获取用户ID
    if (!userId) {
      return reply.code(401).send(errorResponse('用户未登录', 401));
    }
    const result = await taskService.getMyDayTasks(userId);
    return reply.send(successResponse(result, '获取成功'));
  } catch (err) {
    return reply.code(500).send(errorResponse((err as Error).message, 10006));
  }
}

/**
 * 获取任务详情控制器
 * 处理获取特定任务详情的请求
 * @param {FastifyRequest} request - Fastify请求对象，包含任务ID参数
 * @param {FastifyReply} reply - Fastify响应对象
 * @returns {Promise<FastifyReply>} 任务详情响应
 */
async function getTaskDetail(request: FastifyRequest<{ Params: TaskParams }>, reply: FastifyReply): Promise<FastifyReply> {
  try {
    const userId = request.user?.userId; // 从认证中间件获取用户ID
    if (!userId) {
      return reply.code(401).send(errorResponse('用户未登录', 401));
    }
    const { taskId } = request.params;
    const result = await taskService.getTaskDetail(userId, parseInt(taskId));
    return reply.send(successResponse(result, '获取成功'));
  } catch (err) {
    if ((err as Error).message === 'Task not found or access denied') {
      return reply.code(404).send(errorResponse((err as Error).message, 10004));
    }
    return reply.code(500).send(errorResponse((err as Error).message, 10006));
  }
}

/**
 * 更新任务控制器
 * 处理更新任务信息的请求
 * @param {FastifyRequest} request - Fastify请求对象，包含任务ID和更新信息
 * @param {FastifyReply} reply - Fastify响应对象
 * @returns {Promise<FastifyReply>} 更新结果响应
 */
async function updateTask(request: FastifyRequest<{ Params: TaskParams; Body: UpdateTaskBody }>, reply: FastifyReply): Promise<FastifyReply> {
  try {
    const userId = request.user?.userId; // 从认证中间件获取用户ID
    if (!userId) {
      return reply.code(401).send(errorResponse('用户未登录', 401));
    }
    const { taskId } = request.params;
    const { group_id, title, description, is_important, is_my_day, status, due_date } = request.body;
    const result = await taskService.updateTask(
      userId, 
      parseInt(taskId), 
      group_id, 
      title, 
      description, 
      is_important, 
      is_my_day, 
      status ? parseInt(status) : undefined, 
      due_date
    );
    return reply.send(successResponse(result, '更新成功'));
  } catch (err) {
    if ((err as Error).message === 'Task not found or access denied') {
      return reply.code(404).send(errorResponse((err as Error).message, 10004));
    }
    return reply.code(400).send(errorResponse((err as Error).message, 10001));
  }
}

/**
 * 删除任务控制器
 * 处理删除任务的请求
 * @param {FastifyRequest} request - Fastify请求对象，包含任务ID参数
 * @param {FastifyReply} reply - Fastify响应对象
 * @returns {Promise<FastifyReply>} 删除结果响应
 */
async function deleteTask(request: FastifyRequest<{ Params: TaskParams }>, reply: FastifyReply): Promise<FastifyReply> {
  try {
    const userId = request.user?.userId; // 从认证中间件获取用户ID
    if (!userId) {
      return reply.code(401).send(errorResponse('用户未登录', 401));
    }
    const { taskId } = request.params;
    await taskService.deleteTask(userId, parseInt(taskId));
    return reply.send(successResponse({}, '删除成功'));
  } catch (err) {
    if ((err as Error).message === 'Task not found or access denied') {
      return reply.code(404).send(errorResponse((err as Error).message, 10004));
    }
    return reply.code(400).send(errorResponse((err as Error).message, 10001));
  }
}

/**
 * 更新任务分组控制器
 * 处理更新任务所属分组的请求
 * @param {FastifyRequest} request - Fastify请求对象，包含任务ID和新分组ID
 * @param {FastifyReply} reply - Fastify响应对象
 * @returns {Promise<FastifyReply>} 更新结果响应
 */
async function updateTaskGroup(request: FastifyRequest<{ Params: TaskParams; Body: UpdateTaskGroupBody }>, reply: FastifyReply): Promise<FastifyReply> {
  try {
    const userId = request.user?.userId; // 从认证中间件获取用户ID
    if (!userId) {
      return reply.code(401).send({
        code: 401,
        success: false,
        message: '用户未登录',
        data: {}
      });
    }
    const { taskId } = request.params;
    const { group_id } = request.body;
    const result = await taskService.updateTaskGroup(userId, parseInt(taskId), group_id);
    return reply.send(successResponse(result, '更新成功'));
  } catch (err) {
    if ((err as Error).message === 'Task not found or access denied') {
      return reply.code(404).send(errorResponse((err as Error).message, 10004));  
    }
    return reply.code(400).send(errorResponse((err as Error).message, 10001));
  }
}

export default { createTask, getTasks, getMyDayTasks, getTaskDetail, updateTask, deleteTask, updateTaskGroup };



